//
//  PickNum7xcViewController.m
//  PlayBall
//
//  Created by Sun Fanglei on 13-4-2.
//
//

#import "JddPickNum7xcViewController.h"
#import "JddViewControllerManager.h"
#import "NoticeViewController.h"

@interface JddPickNum7xcViewController ()

@end

@implementation JddPickNum7xcViewController

SHARED_VIEW_CONTROLLER_IMPLEMENT(JddPickNum7xcViewController);

@synthesize moneyLabel;
@synthesize countLabel;
@synthesize currIssueLabel;
@synthesize endTimeLabel;
@synthesize currentLotteryIssue;
@synthesize scrollview;

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.message isEqualToString:@"您还没有登录，请先登录"]) {
        if (buttonIndex == 0) {
            countLabel.text = @"0注";
            moneyLabel.text = @"0彩豆";
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOGIN fromController:self withObject:nil withObject2:nil];
        }
    }
}

-(void)listSelect{
//    CGRect rect = [[UIScreen mainScreen] bounds];
//    rect.origin.x = (rect.size.width) / 2.0;
//    rect.origin.y = (rect.size.height) / 2.0;
//    rect.size.width = 251.0;
//    rect.size.height = 300.0;
//    indexList = [JddIndexListView getInstanceView];
//    [indexList setFrame:rect];
//    indexList.type = 0;
//    indexList.delegate = self;
//    [indexList show];
    NoticeViewController *noticeView = [[NoticeViewController alloc] init];
    noticeView.webInfoId = LOTTERY_TYPE_ID_7XC;
    [self.navigationController pushViewController:noticeView animated:YES];
}

//-(void)selectorbutton1{
//    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOTTERY_OPEN_LIST
//                                                         fromController:self
//                                                             withObject:@"3"
//                                                            withObject2:nil];
//}
//
//-(void)selectorbutton2{
//    if (![JddCommonFunction isLogin]) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"玩球球"
//                                                        message:@"您还没有登录，请先登录"
//                                                       delegate:self
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:@"取消", nil]
//        ;
//        [alert show];
//    }else {
//        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_BUY_HISTORY
//                                                             fromController:self
//                                                                 withObject:[NSNumber numberWithInt:LOTTERY_TYPE_ID_7XC]
//                                                                withObject2:nil];
//    }
//}
//
//-(void)selectorbutton3{
//    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_HOW_TO_PLAY_SSQ
//                                                         fromController:self
//                                                             withObject:nil
//                                                            withObject2:nil];
//}
//
//-(void)selectorbutton4{
//    if (![JddCommonFunction isLogin]) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"玩球球"
//                                                        message:@"您还没有登录，请先登录"
//                                                       delegate:self
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:@"取消", nil]
//        ;
//        [alert show];
//    }else {
//        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_FOLLOW_NUMBER_HISTORY
//                                                             fromController:self
//                                                                 withObject:nil
//                                                                withObject2:nil];
//    }
//}

-(void)QueryDigitalLotteryIssueOperationResult:(NSData *)result{
    if (result) {
        if ([JddDataParser parseLotteryIssueResult:result lotteryIssue:currentLotteryIssue]){
            currIssueLabel.text = [NSString stringWithFormat:@"第%@期",currentLotteryIssue.name];
            endTime = [JddCommonFunction dateFromString:currentLotteryIssue.endTime];
            currentTime = [JddCommonFunction dateFromString:currentLotteryIssue.currentTime];
            
            countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                                              target:self
                                                            selector:@selector(countDownTimer:)
                                                            userInfo:nil
                                                             repeats:YES];
        }
    }
}

- (void)countDownTimer:(NSTimer*)thisTimer{
    currentTime = [currentTime dateByAddingTimeInterval:1];
    
    NSTimeInterval interval = [endTime timeIntervalSinceDate:currentTime];
    if (interval == 1) {
        queryState = YES;
        interval = 0;
        [self startQuery];
        return;
        
    } else if(interval>1) {
        NSInteger remainDay = interval / 86400;
        NSInteger remainHour = (interval - 86400 * remainDay) / 3600;
        NSInteger remainMinute = (interval - 86400 * remainDay - remainHour * 3600) / 60;
        NSInteger remainSecond = (interval - 86400 * remainDay - remainHour *3600 - remainMinute * 60);
        endTimeLabel.text = [NSString stringWithFormat:@"%d天%d小时%d分%d秒", remainDay, remainHour, remainMinute, remainSecond];
    }
}


-(void)startQuery{
    [countDownTimer invalidate];
    if (queryState==YES) {
        queryState = NO;
        JddQueryDigitalLotteryIssueOperation *operation = [[JddQueryDigitalLotteryIssueOperation alloc] init];
        operation.delegate = self;
        operation.lotteryTypeId = @"3";
        [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    }
}

- (void)countMoney{
    NSInteger tempCount = 0;
    tempCount = [[lotteryNum BallArray] count]*[[lotteryNum SecondBallArray] count]*[[lotteryNum ThirdBallArray] count]*[[lotteryNum FourthBallArray] count]*[[lotteryNum FifthBallArray] count]*[[lotteryNum SixthBallArray] count]*[[lotteryNum SeventhBallArray] count];
    
    countLabel.text = [NSString stringWithFormat:@"%d注",tempCount];
    moneyLabel.text = [NSString stringWithFormat:@"%d彩豆",tempCount*2];
}

- (void) clearBallState{
    for (UIView *subView in [scrollview subviews] ) {
        if(subView.tag == 11||subView.tag == 2 || subView.tag == 3 || subView.tag == 4 || subView.tag == 5 || subView.tag == 6 || subView.tag == 77){
            [((UIButton*)subView) setSelected:NO];
        }
    }
}

- (void) getRandomNum{
    [lotteryNum clear];
    [self clearBallState];
    [lotteryNum addBallNumber:arc4random()%10];
    [lotteryNum add2BallNumber:arc4random()%10];
    [lotteryNum add3BallNumber:arc4random()%10];
    [lotteryNum add4BallNumber:arc4random()%10];
    [lotteryNum add5BallNumber:arc4random()%10];
    [lotteryNum add6BallNumber:arc4random()%10];
    [lotteryNum add7BallNumber:arc4random()%10];
    float delay = 0.0f;
    for (UIView* inView in [scrollview subviews]) {
        if (inView.tag == 11 && [lotteryNum BallHasNumber:[((UIButton*)inView).titleLabel.text intValue]]) {
            [((UIButton*)inView) setSelected:YES];
            [JddCommonFunction animationViewWithZoomOutIn:inView delaySecond:(delay+=0.05)];
        }else if (inView.tag == 2 && [lotteryNum Ball2HasNumber:[((UIButton*)inView).titleLabel.text intValue]]){
            [((UIButton*)inView) setSelected:YES];
            [JddCommonFunction animationViewWithZoomOutIn:inView delaySecond:(delay+=0.05)];
        }else if (inView.tag == 3 && [lotteryNum Ball3HasNumber:[((UIButton*)inView).titleLabel.text intValue]]){
            [((UIButton*)inView) setSelected:YES];
            [JddCommonFunction animationViewWithZoomOutIn:inView delaySecond:(delay+=0.05)];
        }else if (inView.tag == 4 && [lotteryNum Ball4HasNumber:[((UIButton*)inView).titleLabel.text intValue]]){
            [((UIButton*)inView) setSelected:YES];
            [JddCommonFunction animationViewWithZoomOutIn:inView delaySecond:(delay+=0.05)];
        }else if (inView.tag == 5 && [lotteryNum Ball5HasNumber:[((UIButton*)inView).titleLabel.text intValue]]){
            [((UIButton*)inView) setSelected:YES];
            [JddCommonFunction animationViewWithZoomOutIn:inView delaySecond:(delay+=0.05)];
        }else if (inView.tag == 6 && [lotteryNum Ball6HasNumber:[((UIButton*)inView).titleLabel.text intValue]]){
            [((UIButton*)inView) setSelected:YES];
            [JddCommonFunction animationViewWithZoomOutIn:inView delaySecond:(delay+=0.05)];
        }else if (inView.tag == 77 && [lotteryNum Ball7HasNumber:[((UIButton*)inView).titleLabel.text intValue]]){
            [((UIButton*)inView) setSelected:YES];
            [JddCommonFunction animationViewWithZoomOutIn:inView delaySecond:(delay+=0.05)];
        }
    }
}


- (void)RandomSelectNumViewClickedButtonAtIndex:(NSNumber*)buttonIndex multiple:(NSNumber*)multiple{
    if ([buttonIndex intValue]== 1) {
        
        [lotteryNumArray removeAllObjects];
        
        for (int i = 0; i < [multiple intValue]; ++i) {
            JddFc3dNumber *number = [[JddFc3dNumber alloc] init];
            
            [number addBallNumber:arc4random()%10];
            [number add2BallNumber:arc4random()%10];
            [number add3BallNumber:arc4random()%10];
            [number add4BallNumber:arc4random()%10];
            [number add5BallNumber:arc4random()%10];
            [number add6BallNumber:arc4random()%10];
            [number add7BallNumber:arc4random()%10];

            
            [lotteryNumArray addObject:number];
        }
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_7X_LIST fromController:self withObject:lotteryNumArray withObject2:nil];
    }
}

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
    static NSDate *shakeStart;
    NSDate *now = [[NSDate alloc] init];
    NSDate *checkDate = [[NSDate alloc] initWithTimeInterval:1.5f sinceDate:shakeStart];
    if ([now compare:checkDate] == NSOrderedDescending || shakeStart == nil){
        shakeCount = 0;
        shakeStart = [[NSDate alloc] init];
    }
    
    if (!shaked&&(fabsf(acceleration.x) > 1.0 || fabsf(acceleration.y) > 1.0 || fabsf(acceleration.z) > 1.1)){
        shakeCount++;
    }
    
    if (shakeCount > 0){
        shakeCount = 0;
        shakeStart = [[NSDate alloc] init];
        
        [self getRandomNum];
        [self countMoney];
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)destoryView{
    [lotteryNum clear];
    shaked = true;
    [self clearBallState];
    countLabel.text = [NSString stringWithFormat:@"%d注",0];
    moneyLabel.text = [NSString stringWithFormat:@"%d彩豆",0];
}

-(void)viewWillAppear:(BOOL)animated{
    [MobClick beginLogPageView:@"7XC"];
    [MobClick event:@"Lottery-7XC"];

    shaked = false;
    [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    [[UIAccelerometer sharedAccelerometer] setUpdateInterval:1.0];
    [super viewWillAppear:animated];
    
    
    [countDownTimer invalidate];
    JddQueryDigitalLotteryIssueOperation *operation = [[JddQueryDigitalLotteryIssueOperation alloc] init];
    operation.delegate = self;
    operation.lotteryTypeId = @"3";
    shakeCount = 0;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    [self randomOne:nil];
}

-(void)viewWillDisappear:(BOOL)animated{
    [MobClick endLogPageView:@"7XC"];
    [UIAccelerometer sharedAccelerometer].delegate = nil;
    shaked = true;
}
- (void)loadNavBar
{

    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 40, 30);
    [right setTitle:@"帮助" forState:UIControlStateNormal];
    right.titleLabel.font = [UIFont systemFontOfSize:15];
    [right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(listSelect) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:right];
    
}
//- (void)backView
//{
//    [self.navigationController popViewControllerAnimated:YES];
//}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //[self.navigationItem setTitle:PAGE_7X_PICK_NUMBER];

        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:PAGE_7X_PICK_NUMBER];
        customLab.textAlignment = NSTextAlignmentCenter;

        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;

    [self loadNavBar];
    currentLotteryIssue = [[JddLotteryIssue alloc] init];
    lotteryNum = [[JddFc3dNumber alloc] init];
    lotteryNumArray = [NSMutableArray array];
    [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    [[UIAccelerometer sharedAccelerometer] setUpdateInterval:1.0];
    self.scrollview.showsVerticalScrollIndicator = NO;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setCurrIssueLabel:nil];
    [self setEndTimeLabel:nil];
    [self setCountLabel:nil];
    [self setMoneyLabel:nil];
    [self setScrollview:nil];
    [super viewDidUnload];
}
- (IBAction)clearBtn:(id)sender {
    UIButton *btn = sender;
    [lotteryNum clear];
    [self clearBallState];
    [self countMoney];
    [btn setEnabled:YES];
}

- (IBAction)randomOne:(id)sender{
    [self getRandomNum];
    [self countMoney];
}

- (IBAction)randomBtn:(id)sender {
//    CGRect rect = [[UIScreen mainScreen] bounds];
//    rect.origin.x = (rect.size.width - 251) / 2.0;
//    rect.origin.y = (rect.size.height - 139) / 2.0;
//    rect.size.width = 251.0;
//    rect.size.height = 139.0;
//    randomSelectNumberDialog = [JddRandomSelectNumView getInstanceView];
//    [randomSelectNumberDialog setFrame:rect];
//    randomSelectNumberDialog.type =1;
//    randomSelectNumberDialog.delegate = self;
//    [randomSelectNumberDialog show];
//    UIButton *btn = sender;
//    [self getRandomNum];
//    [self countMoney];
//    [btn setEnabled:YES];
    [lotteryNumArray removeAllObjects];
    
    for (int i = 0; i < 5; ++i) {
        JddFc3dNumber *number = [[JddFc3dNumber alloc] init];
        
        [number addBallNumber:arc4random()%10];
        [number add2BallNumber:arc4random()%10];
        [number add3BallNumber:arc4random()%10];
        [number add4BallNumber:arc4random()%10];
        [number add5BallNumber:arc4random()%10];
        [number add6BallNumber:arc4random()%10];
        [number add7BallNumber:arc4random()%10];
        
        
        [lotteryNumArray addObject:number];
    }
    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_7X_LIST fromController:self withObject:lotteryNumArray withObject2:nil];
}

- (IBAction)doneBtn:(id)sender {
    
    if ([[JddPickNum7xcListViewController sharedInstance].lotNumListTable numberOfRowsInSection:0]>0) {
        if ([countLabel.text intValue]<1) {
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_7X_LIST fromController:self withObject:nil withObject2:nil];
        } else {
            [lotteryNumArray removeAllObjects];
            JddFc3dNumber *newNum = [[JddFc3dNumber alloc] init];
            [newNum.BallArray addObjectsFromArray:lotteryNum.BallArray];
            [newNum.SecondBallArray addObjectsFromArray:lotteryNum.SecondBallArray];
            [newNum.ThirdBallArray addObjectsFromArray:lotteryNum.ThirdBallArray];
            [newNum.FourthBallArray addObjectsFromArray:lotteryNum.FourthBallArray];
            [newNum.FifthBallArray addObjectsFromArray:lotteryNum.FifthBallArray];
            [newNum.SixthBallArray addObjectsFromArray:lotteryNum.SixthBallArray];
            [newNum.SeventhBallArray addObjectsFromArray:lotteryNum.SeventhBallArray];
            [lotteryNumArray addObject:newNum];
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_7X_LIST fromController:self withObject:lotteryNumArray withObject2:nil];
        }
    } else {
        if ([countLabel.text intValue]<1) {
            [JddCommonFunction messageBoxWithMessage:PICK_NUM_N7X_NOT_CORRECT];
        } else {
            [lotteryNumArray removeAllObjects];
            JddFc3dNumber *newNum = [[JddFc3dNumber alloc] init];
            [newNum.BallArray addObjectsFromArray:lotteryNum.BallArray];
            [newNum.SecondBallArray addObjectsFromArray:lotteryNum.SecondBallArray];
            [newNum.ThirdBallArray addObjectsFromArray:lotteryNum.ThirdBallArray];
            [newNum.FourthBallArray addObjectsFromArray:lotteryNum.FourthBallArray];
            [newNum.FifthBallArray addObjectsFromArray:lotteryNum.FifthBallArray];
            [newNum.SixthBallArray addObjectsFromArray:lotteryNum.SixthBallArray];
            [newNum.SeventhBallArray addObjectsFromArray:lotteryNum.SeventhBallArray];
            [lotteryNumArray addObject:newNum];
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_7X_LIST fromController:self withObject:lotteryNumArray withObject2:nil];
        }
    }
}

- (IBAction)numberBtn:(id)sender {
    UIButton *btn = sender;
    [btn setSelected:![btn isSelected]];
    if (btn.tag == 11) {
        if ([btn isSelected]) {
            [lotteryNum addBallNumber:[btn.titleLabel.text intValue]];
        }else{
            [lotteryNum removeBallNumber:[btn.titleLabel.text intValue]];
        }
    }
    if (btn.tag == 2) {
        if ([btn isSelected]) {
            [lotteryNum add2BallNumber:[btn.titleLabel.text intValue]];
        }else{
            [lotteryNum remove2BallNumber:[btn.titleLabel.text intValue]];
        }
    }
    if (btn.tag == 3) {
        if ([btn isSelected]) {
            [lotteryNum add3BallNumber:[btn.titleLabel.text intValue]];
        }else{
            [lotteryNum remove3BallNumber:[btn.titleLabel.text intValue]];
        }
    }
    if (btn.tag == 4) {
        if ([btn isSelected]) {
            [lotteryNum add4BallNumber:[btn.titleLabel.text intValue]];
        }else{
            [lotteryNum remove4BallNumber:[btn.titleLabel.text intValue]];
        }
    }
    if (btn.tag == 5) {
        if ([btn isSelected]) {
            [lotteryNum add5BallNumber:[btn.titleLabel.text intValue]];
        }else{
            [lotteryNum remove5BallNumber:[btn.titleLabel.text intValue]];
        }
    }
    if (btn.tag == 6) {
        if ([btn isSelected]) {
            [lotteryNum add6BallNumber:[btn.titleLabel.text intValue]];
        }else{
            [lotteryNum remove6BallNumber:[btn.titleLabel.text intValue]];
        }
    }
    if (btn.tag == 77) {
        if ([btn isSelected]) {
            [lotteryNum add7BallNumber:[btn.titleLabel.text intValue]];
        }else{
            [lotteryNum remove7BallNumber:[btn.titleLabel.text intValue]];
        }
    }
    if(btn.selected)
    {
        [JddCommonFunction animationViewWithZoomOutIn:btn delaySecond:0];
    }
    [self countMoney];
    [btn setEnabled:YES];
}

@end
